package com.team407.cheyoubang.net;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;

import com.team407.cheyoubang.bean.RequestBean;
import com.team407.cheyoubang.callback.NetCallBack;
import com.team407.cheyoubang.parse.ParseData;
import com.team407.cheyoubang.parse.Result;
import com.team407.cheyoubang.utils.Constant;
import com.team407.cheyoubang.utils.Utils;



import android.os.Handler;

public class Com {
	private Handler mHandler;
	public Com(){
		mHandler = new Handler();
	}
	
	public void doPost(RequestBean requestBean, ParseData parseData, NetCallBack netCallBack){
		Request request = new Request();
		int code = Constant.ErrorCode.SUCCESS;
		Result result = null;
		try {
			String json = request.doPost(requestBean.requestUrl, requestBean.getMap(), "utf-8");
			if(Utils.isEmpty(json)){
				code = Constant.ErrorCode.NET_ERROR;
			}else{
				result = parseData.parse(json);
			}
		} catch (ClientProtocolException e) {
			code = Constant.ErrorCode.NET_ERROR;
			e.printStackTrace();
		} catch (IOException e) {
			code = Constant.ErrorCode.NET_ERROR;
			e.printStackTrace();
		} finally{
			if(Constant.ErrorCode.SUCCESS == code && result == null){
				code = Constant.ErrorCode.PARSE_ERROR;
			}
			
			pushCallBakc(code, result, requestBean.requestUrl, netCallBack);
		}
	}
	
	public void doJsonPost(RequestBean requestBean, ParseData parseData, NetCallBack netCallBack){
		Request request = new Request();
		int code = Constant.ErrorCode.SUCCESS;
		Result result = null;
		try {
			String json = request.doJsonPost(requestBean.requestUrl, requestBean.toString(), "utf-8");
			if(Utils.isEmpty(json)){
				code = Constant.ErrorCode.NET_ERROR;
			}else{
				result = parseData.parse(json);
			}
		} catch (ClientProtocolException e) {
			code = Constant.ErrorCode.NET_ERROR;
			e.printStackTrace();
		} catch (IOException e) {
			code = Constant.ErrorCode.NET_ERROR;
			e.printStackTrace();
		} finally{
			if(Constant.ErrorCode.SUCCESS == code && result == null){
				code = Constant.ErrorCode.PARSE_ERROR;
			}
			
			pushCallBakc(code, result, requestBean.requestUrl, netCallBack);
		}
	}
	
	private void pushCallBakc(final int code, final Result result, final String url, final NetCallBack netCallBack){
		mHandler.post(new Runnable() {
			
			@Override
			public void run() {
				if(code == Constant.ErrorCode.SUCCESS){
					netCallBack.netSuccess(url, result);
				}else{
					netCallBack.netError(url, code);
				}
				
			}
		});
	}
}
